package com.cby.jetpack.sample.paging3

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.LinearLayoutManager
import com.cby.jetpack.sample.databinding.ActivityGankGirlListBinding
import com.cby.jetpack.sample.ext.binding
import com.cby.jetpack.sample.ext.showToast
import com.cby.jetpack.sample.paging3.adapter.GankGirlListAdapter
import com.cby.jetpack.sample.paging3.adapter.LoadStateFooterAdapter
import com.cby.jetpack.sample.paging3.state.EmptyCallback
import com.cby.jetpack.sample.paging3.state.LoadingCallback
import com.cby.jetpack.sample.paging3.state.TimeoutCallback
import com.cby.jetpack.sample.paging3.viewmodel.GankGirlViewModel
import com.cby.operation.common.util.NetworkUtils
import com.cby.jetpack.sample.paging3.state.ErrorCallback
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * @description: GankListActivity
 *
 * @author ChenBaoyang
 * @date 8/12/21 11:16
 */
class GankGirlListActivity : AppCompatActivity() {

    private val tag = "gank-girl"

    private lateinit var loadService: LoadService<*>

    private lateinit var viewModel: GankGirlViewModel

    private lateinit var adapter: GankGirlListAdapter

    private val binding: ActivityGankGirlListBinding by binding()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewModel = ViewModelProvider.AndroidViewModelFactory.getInstance(application).create(
            GankGirlViewModel::class.java
        )

        bindLoadState()

        binding.recyclerView.layoutManager = LinearLayoutManager(this@GankGirlListActivity)
        binding.recyclerView.setHasFixedSize(true)
        adapter = GankGirlListAdapter(){
            position, girlBean, listAdapter ->
            kotlin.run {
                showToast("position = $position , author = ${girlBean?.author}")
                girlBean?.author = "测试${position}"
                listAdapter.notifyDataSetChanged()
            }
        }
        val footAdapter = LoadStateFooterAdapter{
            showToast("重新加载")
        }
        adapter.withLoadStateFooter(footAdapter)
        binding.recyclerView.adapter = adapter



        lifecycleScope.launch {
            adapter.loadStateFlow.collectLatest {
                when (it.refresh) {
                    is LoadState.NotLoading -> {
                        //NotLoading: 当没有加载动作并且没有错误的时候
                        Log.i(tag, "is not loading")
                        loadService.showSuccess()

                    }
                    is LoadState.Loading -> {
                        //Loading: 正在加载
                        Log.i(tag, "is loading")
                        loadService.showCallback(LoadingCallback::class.java)
                    }
                    is LoadState.Error -> {
                        //Error: 加载错误
                        Log.i(tag, "is error")
                        loadService.showCallback(if(NetworkUtils.isConnected(this@GankGirlListActivity)) {
                            ErrorCallback::class.java
                        } else {
                            TimeoutCallback::class.java
                        })
                    }
                }
            }
        }

        binding.btnQuery.setOnClickListener {
            load()
        }
    }

    private fun load() {
        lifecycleScope.launch {
            viewModel.getGirlData().collect {
                adapter.submitData(it)
            }
        }
    }

    private fun bindLoadState() {
        // Your can change the callback on sub thread directly.
        val loadSir = LoadSir.Builder()
            .addCallback(LoadingCallback())
            .addCallback(EmptyCallback())
            .addCallback(ErrorCallback())
            .addCallback(TimeoutCallback())
            //.setDefaultCallback(LoadingCallback::class.java)
            .build()
        loadService = loadSir.register(binding.recyclerView) {
            load()
        }
    }
}